$(function() {
      $.get("http://kassandra614.nog.sgsnet.se:8080/dealfinder/tag/getTags", function(data){
        for (p in data.tags) {
          var $ctrl = $('<input/>').attr({type: 'radio', name:'rad', value: data.tags[p].id}).addClass("category_button");
          var $label = $('<label/>').text(data.tags[p].name);
          var $img = $('<img/>').attr({ src:'http://kassandra614.nog.sgsnet.se:8080/dealfinder/tag/displayImage/' + data.tags[p].id });
          $("#radioDiv").append($ctrl);
          $("#radioDiv").append($img);
          $("#radioDiv").append($label);
        }
      } , "jsonp");
      
      var map;
      var markers = new Array();
      var infowindow = new google.maps.InfoWindow({
        content: "no information"
      });
      var mapOptions = {
        zoom: 13,
        center: new google.maps.LatLng(57.68, 0),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      

      
      if($('#map_canvas').length){ // does #map_canvas exist?
        map = new google.maps.Map($("#map_canvas").get(0), mapOptions);
        geocoder = new google.maps.Geocoder;
        /*$.getJSON('entries.json', function(data) {
          $.each(data, function(i,entry){
            console.log(entry.position,entry.title);
            var latlng = entry.position.split(',');
            var pos = new google.maps.LatLng(latlng[0],latlng[1]);
            console.log(pos.toString())
          });
        });*/
        // Try W3C Geolocation (Preferred)
        if(navigator.geolocation) {
          browserSupportFlag = true;
          navigator.geolocation.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
            map.setCenter(initialLocation);
            var marker = new google.maps.Marker({
                position: initialLocation,
                map: map,
                title:"Here you are"
            });
            marker.setMap(map);
          }, function() {
            handleNoGeolocation(browserSupportFlag);
          });
        // Try Google Gears Geolocation
        } else if (google.gears) {
          browserSupportFlag = true;
          var geo = google.gears.factory.create('beta.geolocation');
          geo.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
            map.setCenter(initialLocation);
          }, function() {
            handleNoGeoLocation(browserSupportFlag);
          });
        // Browser doesn't support Geolocation
        } else {
          browserSupportFlag = false;
          handleNoGeolocation(browserSupportFlag);
        }

        function handleNoGeolocation(errorFlag) {
          if (errorFlag == true) {
            alert("Geolocation service failed.");
            initialLocation = newyork;
          } else {
            alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
            initialLocation = siberia;
          }
          map.setCenter(initialLocation);
        }
      }
      
    function removeAllMarkers(){
      for(var i=0; i<markers.length; i++){
          markers[i].setMap(null);
      }
      markers.length = 0;
    }
    
    $('html').css('background-image', 'url("http://kassandra614.nog.sgsnet.se:8080/dealfinder/city/displayImage/1")');
    
  function getDealMarkers() {
    $.get("http://kassandra614.nog.sgsnet.se:8080/dealfinder/deal/getDeals", function(data){
    for (p in data.deals) {
      setMarkers(p, data);
    }
  } , "jsonp");
}

  function setMarkers(p, data){
      geocoder.geocode( { 'address' : data.deals[p].address}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            marker = new google.maps.Marker({
              map: map,
              position: results[0].geometry.location,
              title: data.deals[p].name,
              icon: 'http://kassandra614.nog.sgsnet.se:8080/dealfinder/tag/displayImage/' + data.deals[p].tag.id,
              html: data.deals[p].name + '<br/>' + '<button type =' + "button" + ' id=' + "submitDeal"
               + ' value=' + data.deals[p].id + '> Purchase the Deal </button>' + '<div id='+ "timerDiv" + '>Diven är här</div>'
                + '<button type =' + "button" + ' id=' + "testCounter" + ' value=' + data.deals[p].endTime + '> addTimer </button>',
              id: data.deals[p].id,
              endTime: data.deals[p].endTime
            });
            var $label = $('<label/>').text(data.deals[p].name);
            $("#content").append($label);
            google.maps.event.addListener(marker, 'click', function() {
              google.maps.event.addListener(infowindow, 'domready', addTimer(this.endTime));
              infowindow.setContent(this.html);
              infowindow.open(map, this);
            });
            markers[markers.length] = marker;
          } 
          else {
            alert("Geocode was not successful for the following reason: " + status);
          }
      });
    }
              
              
  $(".button").click(function() {
    alert("You have now registered:)");
    });
  //$("#hidden_div").hide();
  $("#show_hidden_div").click(function() {
    if($("#hidden_div").is(':visible')) {
      $("#hidden_div").fadeOut("slow");
    }
    else {
      $("#hidden_div").fadeIn("slow");
      }
  });
  
  $(".button_ajax").click(function() {
      $.get("http://localhost:8080/dealfinder/tag/getTags", function(data){
        for (p in data.tags) {
          var $ctrl = $('<input/>').attr({type: 'radio', name:'rad', value: data.tags[p].id}).addClass("category_button");
          var $label = $('<label/>').text(data.tags[p].name);
          var $img = $('<img/>').attr({ src:'http://kassandra614.nog.sgsnet.se:8080/dealfinder/tag/displayImage/' + data.tags[p].id });
          $("#radioDiv").append($ctrl);
          $("#radioDiv").append($img);
          $("#radioDiv").append($label);
        }
      } , "jsonp");
    });
        
    $(".category_button").live('click', function(){
      $.post("http://kassandra614.nog.sgsnet.se:8080/dealfinder/tag/setTag", {id: $(":checked").val()});
      removeAllMarkers();
      getDealMarkers();
    });

		var JSONS = getDeals();/**Getting the deals as JSONS as well as appending them to the carousel, assigning IDs and folding the unused ones*/
    getDealMarkers(); //assigning initia markers
		$("div#leftArrowContainer").click(function(event)
			{
				if(leftMost>=1 && (rightMost)<NumberOfImages)
				{
					var QueryObj = "img#carouselImage"+leftMost;
					$(QueryObj).animate
					(
						{
							width: 'toggle'
						},100
					);
					var QueryObj = "img#carouselImage"+(rightMost+1)
					$(QueryObj).animate
					(
						{
							width: 'toggle'
						},100
					);
					
					leftMost = (leftMost+1);
					rightMost = (rightMost+1);
				}
			});
		
		
		$("div#rightArrowContainer").click(function(event){
				if(leftMost>1)
				{
					var QueryObj = "img#carouselImage"+rightMost;
					$(QueryObj).animate
					(
						{
							width: 'toggle'
						},100
					);
					var QueryObj = "img#carouselImage"+(leftMost-1)
					$(QueryObj).animate
					(
						{
							width: 'toggle'
						},100
					);
					
					leftMost = (leftMost-1);
					rightMost = (rightMost-1);
				}
		});	
			
		$("#backMap").click(function(event){
					document.querySelector("#map_canvas").style.visibility = "visible";
					document.querySelector("#dealsDisplay").style.visibility = "hidden";
	  });
	  
	  
    $("#load_deals").click(function() {
      removeAllMarkers();
      getDealMarkers();
    });
    
    $("#submitDeal").live('click', function(){
      var $firstName = $("#firstName").val();
      var $lastName = $("#lastName").val();
      var $phoneNumber = $("#phoneNumber").val();
      $.post("http://kassandra614.nog.sgsnet.se:8080/dealfinder/user/submitDeal", {firstName: $firstName.toString(), lastName: $lastName.toString(), phoneNumber: $phoneNumber.toString(), dealId: $(this).attr("value")},
        function(data){
            alert(data.result);
        }, "jsonp");
    });
    
    function addTimer(endTime){
      $("#timerDiv").countdown({until: new Date(endTime)});
    }
    
    $('#testCounter').live('click',function() {
      addTimer($(this).attr("value"));
    });
    
});